import datetime
from urllib.parse import urlparse
from fastapi.responses import ORJSONResponse
from fastapi.routing import APIRouter
from logs.settings import logger
from views.spider_test.func.request import *
from extensions import MonConn

router = APIRouter(
    prefix="/api",
    tags=["index"],
    default_response_class=ORJSONResponse
)


@router.post('/spider/test', summary='请求测试', description='', )
async def ApiSpider(query: dict):
    try:
        url = query.get('url')
        task = query.get('task')
        data = query.get('data', None)
        header = query.get('header')
        header = header if header else {"Accept": "application/json, text/plain, */*",
                                        "Accept-Encoding": "gzip, deflate, br",
                                        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", "Cache-Control": "no-cache",
                                        "Content-Type": "",
                                        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"}
        header = eva(header)
        method = query.get('method', 'get')
        timeout = query.get('timeout', '120')
        encode = query.get('encode', 'utf-8')
        verify = query.get('verify', True)
        host = urlparse(url).hostname
        reqdict = {
            'method': method,
            'url': url,
            'data': data,
            'header': header,
            'verify': verify,
            'encode': encode,
            'timeout': timeout
        }
        response = Request.get(**reqdict)
        encoding = response.encoding
        elapsed = response.elapsed
        result = {
            "code": response.status_code,
            "task": task,
            "host": host,
            "time": datetime.datetime.now(),
            "data": {
                "url": url,
                "data": data,
                "method": method,
                "encoding": encoding,
                "elapsed": elapsed.total_seconds(),
                "response": response.headers,
                "content": response.text,
                "request": header,
                "cookie": response.cookies.get_dict(),
                "code": response.status_code,
            }
        }
        MonConn.insert('data', result)
        del result['_id']
        return result
    except Exception as e:
        print(e)
        return {"msg": "error", "detail": e}


def eva(item):
    try:
        return eval(item)
    except:
        return item
